package com.huatai.datacenter.mapper;

import com.huatai.datacenter.entity.TbFireDataRequestLogEntity;
import com.huatai.datacenter.entity.dto.RequestLogDto;
import com.huatai.datacenter.entity.dto.RequestLogStatVo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface TbFireDataRequestLogEntityMapper extends BaseMapperAmy<TbFireDataRequestLogEntity>{

    @Select("<script>" +
            "SELECT " +
            "   requestURL, " +
            "   detail AS appKey," +
            "   COUNT(*) AS requestCount, " +
            "   COALESCE(SUM(dataNum), 0) AS totalData, " +
            "   COALESCE(SUM(CASE WHEN requestStatus = 'success' THEN dataNum ELSE 0 END), 0) AS successData, " +
            "   COALESCE(SUM(CASE WHEN requestStatus = 'error' THEN dataNum ELSE 0 END), 0) AS errorData, " +
            "   ROUND( " +
            "       COALESCE( " +
            "           SUM(CASE WHEN requestStatus = 'success' THEN dataNum ELSE 0 END) * 100.0 / NULLIF(SUM(dataNum), 0), " +
            "           0 " +
            "       ), 2 " +
            "   ) AS successRate " +
            "FROM tb_fire_data_request_log " +
            "WHERE 1=1 " +
            "<if test='dto.appKey != null and dto.appKey != \"\"'>" +
            "   AND detail->>'$.appKey' = #{dto.appKey} " +
            "</if>" +
            "<if test='dto.requestName != null and dto.requestName != \"\"'>" +
            "   AND requestName = #{dto.requestName} " +
            "</if>" +
            "GROUP BY requestURL, detail " +
            "</script>")
    List<RequestLogStatVo> getRequestLogStats(@Param("dto") RequestLogDto dto);


    @Select("select * from tb_fire_data_request_log")
    List<TbFireDataRequestLogEntity> getAll();
}
